<template>
  <div class="small-tab">
    <a-space>
      <span
        v-for="(item, index) of list"
        :key="item.key"
        class="tab-item"
        :class="{ ['active-' + activeColor]: item.key == activeKey }"
        @click.stop="handleTabChange(item, index)"
      >
        {{ item.title }}
      </span>
    </a-space>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";

export default defineComponent({
  name: "SmallTab",
  props: {
    activeKey: {
      type: [Number, String],
      default: "",
    },
    tabList: {
      type: Array,
      default: () => [],
    },
    activeColor: {
      type: String,
      default: "primaryColor",
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      activeKey: "",
      list: [],
    });
    const init = () => {
      const { tabList, activeKey } = props;
      if (activeKey) {
        state.activeKey = activeKey;
        state.list = tabList;
      } else if (tabList.length) {
        if (tabList[0].activeKey) {
          state.activeKey = tabList[0].activeKey;
          state.list = tabList;
        } else {
          state.list = tabList.map((item, index) => ({
            key: index,
            title: item,
          }));
          state.activeKey = 0;
        }
      }
    };
    const handleTabChange = (item, index) => {
      if (state.activeKey == item.key) {
        return;
      }
      emit("change", {
        key: item.key,
        index,
      });
    };

    watch(
      () => props.activeKey,
      (key) => {
        state.activeKey = key;
      }
    );

    onMounted(() => {
      init();
    });

    return {
      ...toRefs(state),
      handleTabChange,
    };
  },
});
</script>
<style lang="less" scoped>
@import "../../styles/vars.less";
.small-tab {
  .tab-item {
    cursor: pointer;
    color: rgba(255, 355, 255, 0.65);
    font-size: 1.2rem;
    position: relative;
    min-width: 8rem;
    padding: 0 1rem;
  }
  .common {
    font-size: 1.4rem;
  }
  .active {
    &-primaryColor {
      //   .common();
      color: #fff;
      &::before {
        content: "";
        position: absolute;
        left: 1rem;
        right: 1rem;
        bottom: -6px;
        height: 3px;
        background: @primaryColor;
        border-radius: 2px;
      }
    }
  }
}
</style>
